package com.ruoyi.system.controller;

import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.util.CharsetUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysArea;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * 地区Controller
 *
 * @author shuyan
 * @date 2020-11-05
 */
@RestController
@RequestMapping("/system/area")
public class SysAreaController extends BaseController {

    @Autowired
    private ISysAreaService sysAreaService;


    /**
     * 查询下级
     *
     * @param useLocale  是否本地地区码
     * @param parentCode 父级区划码
     */
    @RequestMapping("/listByParent")
    public AjaxResult listByParent(Boolean useLocale, String parentCode) {
        List<SysArea> areas = sysAreaService.listByParent(useLocale, parentCode);
        return AjaxResult.success(areas);
    }

    @RequestMapping("/getAreaByLevel")
    public AjaxResult getAreaByLevel(Integer level) {
        String areaCode = SecurityUtils.getLoginUser().getUser().getAreaCode();
        List<SysArea> areas = sysAreaService.listByRootCodeAndLevel(true, areaCode, level);
        return AjaxResult.success(areas);
    }

    /**
     * 查询下级含有人
     *
     * @param useLocale  是否本地地区码
     * @param parentCode 父级区划码
     */
    @RequestMapping("/listByParentUser")
    public AjaxResult listByParentUser(Boolean useLocale, String parentCode) {
        List<SysArea> areas = sysAreaService.listByParentUser(useLocale, parentCode);
        return AjaxResult.success(areas);
    }

    /**
     * 根据节点查询
     */
    @RequestMapping("/getByCode")
    public AjaxResult getByCode(boolean useLocale, String code) {
        SysArea area = sysAreaService.getByCode(useLocale, code);
        return AjaxResult.success(area);
    }

    /**
     * 该地区码以上级别的所有结点
     *
     * @param useLocale 是否本地地区码
     * @param code      查询区划码
     */
    @RequestMapping("/getEachLevelByCode")
    public AjaxResult getEachLevelByCode(boolean useLocale, String code) {
        Map<Integer, SysArea> eachVo = sysAreaService.getEachLevelByCode(useLocale, code);
        return AjaxResult.success(eachVo);
    }

    /**
     * 下载导入模板
     */
    @RequestMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        //写入固定模板内容
        StringBuilder sb = new StringBuilder("name,code\n")
                .append("北京市,11").append("\n")
                .append("市辖区,1101");
        downloadFile(sb.toString().getBytes(), "地区导入模板_以UTF编码.csv", response);
    }

    /**
     * 导入地址码库
     *
     * @param file        导入文件
     * @param useLocale   是否本地地址码
     * @param cleanImport 是否清除后导入
     */
    @RequestMapping("/importAreas")
    public AjaxResult importAreas(MultipartFile file, Boolean useLocale, boolean cleanImport) throws IOException {
        //读取csv内容
        InputStream inputStream = file.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream, CharsetUtil.CHARSET_UTF_8);
        CsvReadConfig readConfig = CsvReadConfig.defaultConfig();
        readConfig.setContainsHeader(true);
        CsvReader csvReader = new CsvReader(readConfig);
        List<Map<String, String>> mapList = csvReader.readMapList(reader);
        //处理数据
        int rows = sysAreaService.importAreas(mapList, useLocale, cleanImport);
        //最终关闭输入流
        reader.close();
        inputStream.close();
        return toAjax(rows);
    }

    /**
     * 从标准库中同步
     */
    @RequestMapping("/syncFromStandard")
    public AjaxResult syncFromStandard() {
        return toAjax(sysAreaService.syncFromStandard());
    }

    /**
     * 保存地区
     * 需求字段: useLocale,id,name,code,parentCode
     */
    @RequestMapping("/saveArea")
    public AjaxResult saveArea(SysArea area) {
        sysAreaService.saveAreaWithCodes(area);
        return AjaxResult.success("操作完成");
    }

    /**
     * 拖拽地区数据
     */
    @PostMapping("/dropArea")
    public AjaxResult dropArea(@RequestBody List<SysArea> areas) {
        return toAjax(sysAreaService.dropArea(areas));
    }

    /**
     * 删除地区
     */
    @RequestMapping("/removeAreas")
    public AjaxResult removeAreas(Boolean useLocale, String code) {
        return toAjax(sysAreaService.removeAreas(useLocale, code));
    }

    /**
     * 删除缓存
     */
    @DeleteMapping("/cleanCaches")
    public AjaxResult cleanCaches() {
        sysAreaService.cleanCaches();
        return AjaxResult.success("操作完成");
    }
}
